package com.github.postsanf.yinian.activity;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.LocalBackUpDayAdapter;
import com.github.postsanf.yinian.bean.ShowBackup;
import com.github.postsanf.yinian.bean.YNImageFloder;
import com.github.postsanf.yinian.bean.YNNativeImage;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.SelectedImg;
import com.github.postsanf.yinian.nativestick.StickyGridHeadersGridView;
import com.github.postsanf.yinian.service.ImportService;
import com.github.postsanf.yinian.utils.YNNativeComparator;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileFilter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

/**
 * 云端备份页面
 */
public class LocalBackUpActivity extends BaseActivity implements View.OnClickListener {
    private ConnectivityManager mConnectivityManager;
    private NetworkInfo netInfo;
    private LocalBackUpDayAdapter mAdapter;                        // 相册适配器
    private StickyGridHeadersGridView mGirdView;                        // 网格布局
    private ProgressDialog mProgressDialog;                // 进度条
    private int mPicsSize;                        // 文件夹图片数量
    private File mImgDir;                        // 图片数量最多的文件夹
    private List<String> mfristImgsnew = new ArrayList<>();
    private TextView tv_select;
    private TextView tv_backup;
    private ImageView start_backup;
    private HashSet<String> mDirPaths = new HashSet<String>();
    private List<YNImageFloder> mImageFloders = new ArrayList<YNImageFloder>();
    private List<YNNativeImage> mNativeImageList = new ArrayList<>();
    private List<YNNativeImage> mNativeImageListMon = new ArrayList<>();
    private Map<String, Integer> sectionMap = new HashMap<>();
    private Map<String, List<YNNativeImage>> dayMap = new HashMap<>();
    private Map<String, List<YNNativeImage>> monMap = new HashMap<>();
    private static int section = 1;
    private boolean dayTime = true;
    private boolean first = true;
    private boolean start = false;
    private int totalPic;
    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0x110:
                    // 为View绑定数据
                    data2View();
                    break;
                case 1:
                    mAdapter = new LocalBackUpDayAdapter(LocalBackUpActivity.this, mNativeImageList, true, dayTime, dayMap, monMap);
                    mGirdView.setAdapter(mAdapter);
                    if (mProgressDialog != null)
                        mProgressDialog.dismiss();
                    checkNetWork();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerBoradcastReceiver();
        setContentView(R.layout.yn_activity_local_backup);
        initView();
        getImages();
    }

    private void checkNetWork() {
        if (netInfo != null && netInfo.isAvailable()) {
            if (netInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                //WiFi网络
                Toast.makeText(LocalBackUpActivity.this, "WiFi", Toast.LENGTH_SHORT).show();
                tv_backup.setVisibility(View.VISIBLE);
                tv_backup.setText("正在备份（WiFi）");
                start_backup.setVisibility(View.GONE);
                showBackup();
            } else if (netInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                //3g网络
                Toast.makeText(LocalBackUpActivity.this, "3g网络", Toast.LENGTH_SHORT).show();
                tv_backup.setVisibility(View.VISIBLE);
                tv_backup.setText("暂停备份（流量）");
                start_backup.setVisibility(View.GONE);
            }
        } else {
            //无网络
        }
    }

    private void showBackup() {
        mProgressDialog = ProgressDialog.show(this, "", "");
        String urlsto = getString(R.string.SLIVER_URL) + "GetUserAllPhotoHash";
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        StringRequest req = new StringRequest(urlsto)
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        ShowBackup showBackup = gson.fromJson(s, ShowBackup.class);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if (jsonObject.optString("msg").equals("success")) {


                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (TextUtils.equals(showBackup.getMsg(), "success")) {
                            List<ShowBackup.DataBean> data = showBackup.getData();
                            if (mNativeImageList.size() > data.size()) {
                                UpLoadpic();
                            } else if (mNativeImageList.size() == data.size()) {
                                showToast("已全部备份到云端");
                            }
//                            if (data.size() != 0) {
//                                Intent intent = new Intent(LocalBackUpActivity.this, ImporProgressActivity.class);
//                                intent.putExtra("showBackup", s);
//                                startActivity(intent);
//                                finish();
//                            }
                            Log.i("xjs", "sss==>" + s);
                        } else {
                            Log.d("yuhao", "UploadToYiNian=" + "fail");
                        }
                        if (mProgressDialog != null)
                            mProgressDialog.dismiss();
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        if (mProgressDialog != null)
                            mProgressDialog.dismiss();
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }


    private void UpLoadpic() {
        String s = toJson();
        SharedPreferences sp = getSharedPreferences("nullUpkey", Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString("nullUpkey", s);
        edit.putInt("totalPic", mNativeImageList.size());
        edit.commit();
        toGetProgress();
    }

    boolean network = false;

    private void toGetProgress() {
        SharedPreferences sp = getSharedPreferences("nullUpkey", Context.MODE_PRIVATE);
        totalPic = sp.getInt("totalPic", 0);
        if (first) {
            first = false;
            if (totalPic == 0) {
            } else {
                toStartService();
                int progress = sp.getInt("progress", 0);
            }
        }
        //离开WIFI环境的情况下重新返回WIFI环境下会连续收到两次广播启动两次服务因此延时将first=true;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                first = true;
                start = false;
            }
        }, 20);
    }


    private void toStartService() {
        Intent mIntent = new Intent(this, ImportService.class);
        mIntent.setAction(ACTIONs.actionPublishPhoto);
        mIntent.putExtra(ACTIONs.picNumber, totalPic);
        mIntent.putExtra(ACTIONs.aUid, application.getCurID() + "");
        startService(mIntent);
    }

    private String toJson() {
        JSONObject jsonObject1 = new JSONObject();
        JSONArray jsonArray1 = new JSONArray();
        List<String> localUrl = new ArrayList<>();
        for (int i = 0; i < mNativeImageList.size(); i++) {
            String path = mNativeImageList.get(i).getPath();
            localUrl.add(path);
            SelectedImg.dateUrl.put(getTime(path), localUrl);
        }
        Iterator<Map.Entry<String, List<String>>> it = SelectedImg.dateUrl.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, List<String>> entry = it.next();
            String key = entry.getKey();
            try {
                jsonObject1.put("date", key);
                List<String> value = entry.getValue();
                String url = null;
                for (int i = 0; i < value.size(); i++) {
                    String strings = value.get(i);
                    if (url == null) {
                        url = strings;
                    } else {
                        url = url + "," + strings;
                    }
                }
                jsonObject1.put("photo", url);
                jsonArray1.put(jsonObject1);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return jsonArray1.toString();
    }


//    private void toGetProgress() {
//        SharedPreferences sp = getSharedPreferences("nullUpkey", Context.MODE_PRIVATE);
//        totalPic = sp.getInt("totalPic", 0);
//        picNumber = sp.getInt("picNumber", 0);
//        if (first && network) {
//            first = false;
//            if (totalPic == 0) {
//                rl_import_message.setVisibility(View.GONE);
//                fab_publish_status.setVisibility(View.VISIBLE);
//            } else {
//                rl_import_message.setVisibility(View.VISIBLE);
//                fab_publish_status.setVisibility(View.GONE);
//                toStartService();
//                int progress = sp.getInt("progress", 0);
//                import_progress.setProgress(progress);
//                import_percent.setText(progress + "%");
//                layoutParams.leftMargin = (int) (progress * width * 0.01f);
//                iv_voice_progress.setLayoutParams(layoutParams);
//                fab_publish_status.setVisibility(View.GONE);
//            }
//        }
//        import_total_pic.setText(totalPic + "张");
//        //离开WIFI环境的情况下重新返回WIFI环境下会连续收到两次广播启动两次服务因此延时将first=true;
//        handler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                first = true;
//                start = false;
//            }
//        }, 20);
//    }

    private void initView() {
        mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        netInfo = mConnectivityManager.getActiveNetworkInfo();
        mGirdView = (StickyGridHeadersGridView) findViewById(R.id.gv_album_gridView);
        mGirdView.setAreHeadersSticky(false);
        mGirdView.setNumColumns(3);
        tv_select = ((TextView) findViewById(R.id.tv_select));
        tv_backup = ((TextView) findViewById(R.id.tv_backup));
        start_backup = ((ImageView) findViewById(R.id.start_backup));
        tv_select.setOnClickListener(this);
        findViewById(R.id.backup_back).setOnClickListener(this);
    }

    // 数据绑定
    private void data2View() {
        if (mImgDir == null) {
            showToast("图片没扫描到");
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int j = 0; j < mImageFloders.size(); j++) {
                    mImgDir = new File(mImageFloders.get(j).getDir());
                    File[] files = mImgDir.listFiles(new FileFilter() {
                        @Override
                        public boolean accept(File file) {
                            String filename = file.getName().toLowerCase();
                            if (file.length() > 0 && !filename.contains(".9")) {
                                if (filename.endsWith(".jpg") || filename.endsWith(".png")
                                        || filename.endsWith(".jpeg") || filename.endsWith(".gif"))
                                    return true;
                            }
                            return false;
                        }
                    });
                    if (files != null) {
                        for (int k = 0; k < files.length; k++) {
                            mfristImgsnew.add(files[k].getAbsolutePath());
                        }
                    }
                }
                mNativeImageList.clear();
                mNativeImageListMon.clear();
                for (int i = 0; i < mfristImgsnew.size(); i++) {
                    File file = new File(mfristImgsnew.get(i));
                    String imgPath = file.getPath();
                    long imgTime = file.lastModified();
                    Date currentTime = new Date(imgTime);
                    String dateString = new SimpleDateFormat("yyyy-MM-dd").format(currentTime);
                    YNNativeImage mNativeItem = new YNNativeImage(imgPath, dateString);
                    if (file.length() > 0) {
                        mNativeImageList.add(mNativeItem);
                        if (dayMap.containsKey(dateString)) {
                            List<YNNativeImage> ynNativeImages = dayMap.get(dateString);
                            ynNativeImages.add(mNativeItem);
                        } else {
                            List<YNNativeImage> list = new ArrayList<YNNativeImage>();
                            list.add(mNativeItem);
                            dayMap.put(dateString, list);
                        }
                        String dateStringMon = new SimpleDateFormat("yyyy-MM").format(currentTime);
                        YNNativeImage mNativeItemMon = new YNNativeImage(imgPath, dateStringMon);
                        mNativeImageListMon.add(mNativeItemMon);
                        if (monMap.containsKey(dateStringMon)) {
                            List<YNNativeImage> ynNativeImages = monMap.get(dateStringMon);
                            ynNativeImages.add(mNativeItemMon);
                        } else {
                            List<YNNativeImage> list = new ArrayList<YNNativeImage>();
                            list.add(mNativeItemMon);
                            monMap.put(dateStringMon, list);
                        }
                    }
                }
                Collections.sort(mNativeImageList, new YNNativeComparator());
                for (ListIterator<YNNativeImage> it = mNativeImageList.listIterator(); it.hasNext(); ) {
                    YNNativeImage mNativeItem = it.next();
                    String ym = mNativeItem.getTime();
                    if (!sectionMap.containsKey(ym)) {
                        mNativeItem.setSection(section);
                        sectionMap.put(ym, section);
                        section++;
                    } else {
                        mNativeItem.setSection(sectionMap.get(ym));
                    }
                }
                Collections.sort(mNativeImageListMon, new YNNativeComparator());
                for (ListIterator<YNNativeImage> it = mNativeImageListMon.listIterator(); it.hasNext(); ) {
                    YNNativeImage mNativeItem = it.next();
                    String ym = mNativeItem.getTime();
                    if (!sectionMap.containsKey(ym)) {
                        mNativeItem.setSection(section);
                        sectionMap.put(ym, section);
                        section++;
                    } else {
                        mNativeItem.setSection(sectionMap.get(ym));
                    }
                }
                mHandler.sendEmptyMessage(1);
            }
        }).start();
    }


    /**
     * 利用ContentProvider扫描手机中的图片，此方法在运行在子线程中 完成图片的扫描，最终获得jpg最多的那个文件夹
     */
    private void getImages() {
        if (!Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            showToast("暂无外部存储");
            return;
        }
        // 显示进度条
        mProgressDialog = ProgressDialog.show(this, "", CommonConstants.TIP_LOAD_DATA);
        new Thread(new Runnable() {
            @Override
            public void run() {
                String firstImage = null;
                Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                ContentResolver mContentResolver = LocalBackUpActivity.this
                        .getContentResolver();
                // 只查询jpeg和png的图片
                Cursor mCursor = mContentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null,
                        MediaStore.Images.Media.MIME_TYPE + "=? or "
                                + MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?",
                        new String[]{"image/jpeg", "image/png", "image/gif"},
                        MediaStore.Images.Media.DATE_MODIFIED);
//				Log.e("TAG", mCursor.getCount() + "");
                while (mCursor.moveToNext()) {
                    // 获取图片的路径
                    String path = mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    // 拿到第一张图片的路径
                    if (firstImage == null)
                        firstImage = path;
                    // 获取该图片的父路径名
                    File parentFile = new File(path).getParentFile();
                    if (parentFile == null)
                        continue;
                    String dirPath = parentFile.getAbsolutePath();
                    YNImageFloder imageFloder = null;
                    // 利用一个HashSet防止多次扫描同一个文件夹（不加这个判断，图片多起来还是相当恐怖的~~）
                    if (mDirPaths.contains(dirPath)) {
                        continue;
                    } else {
                        mDirPaths.add(dirPath);
                        // 初始化imageFloder
                        imageFloder = new YNImageFloder();
                        imageFloder.setDir(dirPath);
                        imageFloder.setFirstImagePath(path);
                    }
                    File[] pics = new File(dirPath).listFiles(new FileFilter() {
                        @Override
                        public boolean accept(File file) {
                            String filename = file.getName().toLowerCase();
                            if (filename.toLowerCase().endsWith(".gif") || filename.toLowerCase().endsWith(".jpg") || filename.toLowerCase().endsWith(".png")
                                    || filename.toLowerCase().endsWith(".jpeg"))
                                return true;
                            return false;
                        }
                    });
                    int picSize = (pics != null) ? pics.length : 0;
                    imageFloder.setCount(picSize);
                    mImageFloders.add(imageFloder);
                    if (picSize > mPicsSize) {
                        mPicsSize = picSize;
                        mImgDir = parentFile;
                    }
                }
                mCursor.close();
                // 扫描完成，辅助的HashSet也就可以释放内存了
                mDirPaths = null;
                // 通知Handler扫描图片完成
                mHandler.sendEmptyMessage(0x110);
            }
        }).start();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_select:
                break;
            case R.id.backup_back:
                finish();
                break;
        }
    }

    @Override
    public void onBackPressed() {
        AnimateFirstDisplayListener.displayedImages.clear();
        super.onBackPressed();
        // SelectedImg.mSelectedImage.clear();
    }

    /**
     * 图片加载监听事件
     **/
    public static class AnimateFirstDisplayListener extends
            SimpleImageLoadingListener {

        public static final List<String> displayedImages = Collections
                .synchronizedList(new LinkedList<String>());

        @Override
        public void onLoadingComplete(String imageUri, View view,
                                      Bitmap loadedImage) {
            if (loadedImage != null) {
                ImageView imageView = (ImageView) view;
                boolean firstDisplay = !displayedImages.contains(imageUri);
                if (firstDisplay) {
                    displayedImages.add(imageUri); // 将图片uri添加到集合中
                }
            }
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
//        mAdapter.notifyDataSetChanged();
    }

    // 清除选中并退出
    private void clearAll() {
        finish();
    }

    // 广播接收
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case ACTIONs.actionUpdateProgress:
                    int upProgress = intent.getIntExtra(ACTIONs.aUpProgress, 0);
                    Log.i("xjs", "upppppppppppppp==>" + upProgress);
                    break;
                case ACTIONs.actionCloseAlbum:
                    int noClear = intent.getExtras().getInt(ACTIONs.aIsClearSelect);
                    if (1 == noClear) {
                        finish();
                    } else {
                        Log.d("yuhao", "clearAll");
                        clearAll();
                    }
                    break;
            }
        }
    };

    //注册广播
    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.actionCloseAlbum);
        myIntentFilter.addAction(ACTIONs.actionUpdateProgress);
        this.registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    @Override
    protected void onDestroy() {
        this.unregisterReceiver(mBroadcastReceiver);
        if (mProgressDialog != null)
            mProgressDialog.dismiss();
        super.onDestroy();
    }


    private String getTime(String path) {
        long imgTime = new File(path).lastModified();
        return new SimpleDateFormat("yyyy-MM-dd").format(new Date(imgTime));
    }


    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
